<template>
  <div class="client-manager">
    <DraggableHeaderTab v-model="tableBodyParams" @getList="getManageList" />
    <div class="filter-container">
      <div class="filter-button">
        <el-button type="primary" :icon="Plus" @click="handelShowAddDialog">新建</el-button>
        <el-button type="primary" :icon="Search" plain @click="handelCheckRepeat">查重</el-button>
        <!--        <el-button type="primary" plain @click="handelDistribution">分配</el-button>-->
        <!--        <el-button type="primary" plain @click="handelTransfer">移交</el-button>-->
        <el-button type="primary" plain @click="handelListField">列表字段配置</el-button>
        <el-button class="importBtn" :icon="Download" type="primary" plain @click="handelImport"> 导入</el-button>
        <el-button class="exportBtn" :icon="Upload" type="primary" plain @click="handelExport">导出</el-button>
        <el-button :icon="Switch" type="primary" plain @click="handelTransfer">客户移交</el-button>
      </div>
      <div class="flex-items filter-input">
        <el-select placeholder="请选择" v-model="tableBodyParams.searchType">
          <el-option :value="filterType.CUSTOMER_TYPE" label="客户"></el-option>
          <el-option :value="filterType.RESPONSIBLE_PERSON" label="负责人"></el-option>
        </el-select>
        <div class="flex-items search-container">
          <el-input
            v-model="tableBodyParams.searchValue"
            class="search-input"
            clearable
            placeholder="请输入"
            :suffix-icon="Search"
            @keyup.enter="handelSearch"
          />
          <el-button type="primary" :icon="Search" @click="handelSearch">查询</el-button>
          <el-button type="primary" plain :icon="RefreshRight" @click="handelResetFilter">重置</el-button>
        </div>
      </div>
    </div>
    <div class="table-container" v-loading="isLoading" element-loading-text="数据加载中...">
      <div class="table-container-filter">
        <div class="allocation">
          <span>已勾选：{{ selectCustomersArr.length }}</span>
          <el-button type="primary" plain :disabled="selectCustomersArr.length == 0" @click="showMultipleAllocation = true"
            >批量分配</el-button
          >
        </div>
        <div class="check-box">
          <el-checkbox v-model="tableBodyParams.unallocatedValue" label="未分配" size="large" @change="changeAllocationStatus" />
          <el-checkbox v-model="tableBodyParams.lost" label="流失客户" size="large" @change="changeLostStatus" />
        </div>
      </div>
      <el-table
        ref="clientManagerRef"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
        row-key="customerId"
        border
        :header-cell-style="{ background: '#F2F6FC', color: '#909399', 'font-weight': 400, 'font-size': '14px' }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="selection" width="50" :reserve-selection="true" />
        <CustomTableColumn :tableHeaders="tableHeaders" @customFilter="handelCustomFilter" @previewFile="previewFile" />
        <el-table-column v-if="tableHeaders.length" fixed="right" width="200">
          <template #default="{ row }">
            <div class="table-buttons" v-if="row.status !== clientStatus.LOST">
              <el-button type="primary" link size="small" @click="handelDistribution(row)">分配</el-button>
              <!--              disabled-->
              <el-button type="primary" v-if="!row.start_apply" link size="small" @click="handleApplyWork(row)"
                >申请开工</el-button
              >
              <el-button type="primary" link size="small" @click="handelResetTask(row)">重置任务</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <custom-pagination
      :total="listTotal"
      v-model:limit="tableParams.size"
      v-model:page="tableParams.current"
      layout="total, slot, prev, pager, next, jumper"
      @pagination="handelPage"
    >
      <template #default>
        <el-select style="margin-left: 16px" v-model="tableParams.size" @change="handelPageSize">
          <el-option
            v-for="(item, index) in pageSizeList"
            :key="`${item.label}-${index}`"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </template>
    </custom-pagination>

    <AddClient v-if="isShowAddDialog" v-model="isShowAddDialog" @submit="getManageList" />

    <AllocationTransfer
      v-if="isShowTransferDialog"
      v-model="isShowTransferDialog"
      :dialogTitle="dialogTransferTitle"
      :optionType="optionType"
      :customerIds="customerIds"
    />

    <CheckRepeat v-if="isShowRepeatDialog" v-model="isShowRepeatDialog" />

    <TransferDialog v-if="isShowTransfer" v-model="isShowTransfer" @transfer-confirm="handelTransferData" />

    <ImportData v-if="isShowImportDialog" v-model="isShowImportDialog" @import-confirm="handleImportConfirm" />
    <ExportData v-if="isShowExportDialog" v-model="isShowExportDialog" :tableBodyParams="tableBodyParams" />

    <CustomerTransfer
      v-if="isShowCustomerTransferDialog"
      v-model="isShowCustomerTransferDialog"
      @save="handleSave"
      :tableBodyParams="tableBodyParams"
    />

    <!--  预览图片/视频  -->
    <media-viewer v-if="isShowPreview" :urlList="previewUrlList" @close="closeViewer"></media-viewer>
    <!--  预览文件/富文本  -->
    <previewFileOrEditor v-model="isShowPreviewDialog" :content="fileOrEditor"></previewFileOrEditor>

    <!--    开工申请-->
    <applay-work
      v-if="showApplyWork"
      v-model="showApplyWork"
      @workApplySave="getManageList"
      :customerId="customerId"
    ></applay-work>
    <!--    批量分配-->
    <multiple-allocation
      v-if="showMultipleAllocation"
      v-model="showMultipleAllocation"
      @multipleAllocationSave="multipleAllocationSave"
      :selectCustomersArr="selectCustomersArr"
    ></multiple-allocation>
  </div>
</template>

<script>
import cmps from "./components";
export default {
  name: "clientManager",
  components: {
    ...cmps
  }
};
</script>
<script setup>
import { ref, computed, getCurrentInstance, onActivated } from "vue";
import { Search, Plus, RefreshRight, Upload, Download, Switch } from "@element-plus/icons-vue";
import { cloneDeep, debounce } from "lodash";
import { useRouter, useRoute } from "vue-router";
import { pageSizes } from "@/config/config";
import {
  allocationTransferType,
  filterType,
  tableBody as tableQuery,
  clientStatus,
  previewImgType,
  previewVideoType
} from "./config";
import { tableRowClassName } from "@/views/client/utils";
import { parseOrDefault } from "@/utils";
import { listManage, customManageTableHeader, resetClientInfo } from "@/apis/clientManager";
import areaData from "@/assets/pca-code";
import useTagsViewStore from "@/store/modules/tagsView";
import ApplayWork from "./components/ApplyWork";
import MultipleAllocation from "./components/MultipleAllocation";

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const tagsViewStore = useTagsViewStore();

/**
 * 列表
 */
const clientManagerRef = ref(null);
const isLoading = ref(false);
const tableParams = ref({
  current: 1,
  size: 10
});
const tableBodyParams = ref({ ...tableQuery });
const tableHeaders = ref([]);
const listTotal = ref(0);
const tableData = ref([]);
const pageSizeList = computed(() => {
  const sizes = [...pageSizes];
  // sizes[sizes.length - 1].value = listTotal.value;
  return sizes;
});
const getAreaLabelsByCode = (areaData, codes) => {
  if (!Array.isArray(areaData)) {
    return new Error("areaData must be array");
  }
  if (!Array.isArray(codes)) {
    return new Error("codes must be array");
  }
  const labels = [];
  const codeSet = new Set(codes);
  const inverseAnalysis = areaData => {
    for (const item of areaData) {
      if (codeSet.has(`${item.id}`)) {
        labels.push(item.name);
        codeSet.delete(`${item.id}`);
        if (codeSet.size === 0) return;
      }
      if (item.children?.length) {
        inverseAnalysis(item.children);
        if (codeSet.size === 0) return;
      }
    }
  };
  inverseAnalysis(areaData);
  return labels;
};
const handelTableData = data => {
  let listData = data?.list || [];
  let addressFieldArr =
    tableHeaders.value?.filter(
      item => (item.fieldName === "CascaderInput" && item.fieldId !== "fitment_area_ids") || item.fieldName === "UserPicker"
    ) || [];
  if (!addressFieldArr?.length) return listData;
  addressFieldArr.forEach(headerItem => {
    listData.forEach(listItem => {
      if (Object.keys(listItem).includes(headerItem.fieldId)) {
        if (headerItem.fieldName === "UserPicker") {
          const userData = listItem[headerItem.fieldId] ? JSON.parse(listItem[headerItem.fieldId]) : [];
          listItem[headerItem.fieldId] = userData?.map(item => item.name)?.join(",") || "";
        }
        if (headerItem.fieldName === "CascaderInput") {
          listItem[headerItem.fieldId] =
            getAreaLabelsByCode(areaData, listItem[headerItem.fieldId]?.split(",") || [])
              ?.join(",")
              ?.replace(/,/g, "/") || "";
        }
      }
    });
  });
  return listData;
};
const getManageList = async () => {
  try {
    isLoading.value = true;
    const postData = cloneDeep(tableBodyParams.value);
    if (tableBodyParams.value.unallocatedValue) {
      postData.unallocatedValue = filterType.FIXED_COLUMN_BUTTON;
    } else {
      postData.unallocatedType = "";
      postData.unallocatedValue = "";
    }
    if (tableBodyParams.value.customType === filterType.CUSTOM_QUERY) {
      const customValue = [
        {
          groupType: "AND",
          conditions: tableHeaders.value.filter(item => item.compare)
        }
      ];
      postData.customValue = JSON.stringify(customValue);
    } else {
      postData.customValue = "";
    }
    if (!tableHeaders.value?.length) {
      const { data: headerData } = await customManageTableHeader();
      tableHeaders.value = headerData;
    }
    const { data } = await listManage(postData, tableParams.value);
    tableData.value = handelTableData(data);
    listTotal.value = data?.total ?? 0;
    isLoading.value = false;
  } catch (err) {
    isLoading.value = false;
  }
};
const handelSearch = debounce(() => {
  tableParams.value.current = 1;
  tableData.value = [];
  getManageList();
}, 500);
const handelResetFilter = debounce(() => {
  tableBodyParams.value = { ...tableQuery };
  tableHeaders.value.forEach(item => {
    item.value = [];
    item.compare = "";
    item.isCondition = false;
  });
  getManageList();
}, 500);
const handelPage = () => {
  tableData.value = [];
  getManageList();
};
const handelPageSize = () => {
  tableParams.value.current = 1;
  tableData.value = [];
  getManageList();
};

/**
 * 未分配
 */
const changeAllocationStatus = data => {
  tableBodyParams.value.unallocatedType = data ? filterType.UNALLOCATED : "";
  tableParams.value.current = 1;
  tableData.value = [];
  getManageList();
};
/**
 * 流失客户
 */
const changeLostStatus = () => {
  tableParams.value.current = 1;
  tableData.value = [];
  getManageList();
};

const isShowAddDialog = ref(false);
const handelShowAddDialog = () => {
  isShowAddDialog.value = true;
};

const isShowRepeatDialog = ref(false);
const handelCheckRepeat = () => {
  isShowRepeatDialog.value = true;
};

const isShowTransferDialog = ref(false);
const dialogTransferTitle = ref("");
const optionType = ref(allocationTransferType.ALLOCATION);
const customerIds = ref([]);
const handelDistribution = data => {
  router.push({
    path: "/distribution",
    query: {
      customerId: data.customerId,
      reformType: false,
      stageType: 1
    }
  });
};

const handelResetTask = data => {
  proxy.$modal
    .confirm("除该客户已完成的任务外，其他任务将按最新流程模板重发，是否确认？", "确认操作？")
    .then(async () => {
      try {
        isLoading.value = true;
        await resetClientInfo(data.customerId);
        isLoading.value = false;
        proxy.$modal.msgSuccess("重置成功");
      } catch (err) {
        isLoading.value = false;
      }
    })
    .catch(() => {});
};

const isShowTransfer = ref(false);
const handelListField = () => {
  isShowTransfer.value = true;
};
const handelTransferData = () => {
  isShowTransfer.value = false;
  tableHeaders.value = [];
  getManageList();
};

const handelCustomFilter = data => {
  const { fieldData, columnIndex } = data;
  tableHeaders.value[columnIndex] = fieldData;
  if (data.isRefresh) {
    tableBodyParams.value.customType = filterType.CUSTOM_QUERY;
    getManageList();
  }
};

/**
 * 预览图片/视频/文件/富文本
 */
const isShowPreview = ref(false);
const isShowPreviewDialog = ref(false);
const fileComponent = ["VideoUpload", "ImageUpload", "FileUpload"];
const previewUrlList = ref([]);
const fileOrEditor = ref("");
const previewFile = ({ row, headerItem }) => {
  const fileData = fileComponent.includes(headerItem.fieldName)
    ? parseOrDefault(row[headerItem.fieldId], [])
    : row[headerItem.fieldId];
  if (["VideoUpload", "ImageUpload"].includes(headerItem.fieldName)) {
    previewUrlList.value = fileData?.map(item => item.fileUrl) || [];
    if (!previewUrlList.value.length) return proxy.$modal.msgError("无预览内容");
    isShowPreview.value = true;
  }
  if (["FileUpload", "EditorInput"].includes(headerItem.fieldName)) {
    fileOrEditor.value = fileData;
    if (!fileOrEditor.value || (Array.isArray(fileOrEditor.value) && !fileOrEditor.value.length))
      return proxy.$modal.msgError("无预览内容");
    isShowPreviewDialog.value = true;
  }
};
const closeViewer = () => {
  isShowPreview.value = false;
};

//导入
const isShowImportDialog = ref(false);
const handelImport = () => {
  isShowImportDialog.value = true;
};
const handleImportConfirm = () => {
  isShowImportDialog.value = false;
  getManageList();
};
//导出
const isShowExportDialog = ref(false);
const handelExport = () => {
  isShowExportDialog.value = true;
};

// 移交
const isShowCustomerTransferDialog = ref(false);
const handelTransfer = () => {
  isShowCustomerTransferDialog.value = true;
};
const handleSave = () => {
  getManageList();
};

const initData = () => {
  const unAssigned = route.query?.unAssigned ?? "0";
  tableBodyParams.value.unallocatedType = unAssigned == 1 ? "5" : "";
  tableBodyParams.value.unallocatedValue = unAssigned == 1;
  tagsViewStore.isRefresh = false;
  getManageList();
};

// 申请开工
const customerId = ref("");
const showApplyWork = ref(false);
const handleApplyWork = row => {
  showApplyWork.value = true;
  customerId.value = row.customerId;
};

//批量分配
const selectCustomersArr = ref([]);
const showMultipleAllocation = ref(false);
const handleSelectionChange = selections => {
  selectCustomersArr.value = selections.map(item => item.customerId);
};
const multipleAllocationSave = () => {
  selectCustomersArr.value = [];
  clientManagerRef.value.clearSelection();

  getManageList();
};

onActivated(() => {
  tagsViewStore.isRefresh && handelResetFilter();
});

initData();
</script>

<style scoped lang="scss">
@use "clientManager";
</style>
